package com.itmuch;

import com.dianping.cat.Cat;
import com.itmuch.common.cat.CatMsgConstants;
import org.slf4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.io.IOException;

/**
 * Created by xi on 2018/8/5.
 */
public class RestUserAgentInterceptor implements ClientHttpRequestInterceptor {
    private Logger logger = org.slf4j.LoggerFactory.getLogger(RestUserAgentInterceptor.class);
    /**
     * RestTemplate请求加上默认请求头（签名、时间轴）
     * @param request
     * @param body
     * @param execution
     * @return
     */
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders headers = request.getHeaders();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        Object root = requestAttributes.getAttribute(Cat.Context.ROOT, 0);
        if(root!=null){
            String rootId = requestAttributes.getAttribute(Cat.Context.ROOT, 0).toString();
            String childId = requestAttributes.getAttribute(Cat.Context.CHILD, 0).toString();
            String parentId = requestAttributes.getAttribute(Cat.Context.PARENT, 0).toString();
            headers.add(Cat.Context.ROOT, rootId);
            headers.add(Cat.Context.CHILD, childId);
            headers.add(Cat.Context.PARENT, parentId);
            headers.add(CatMsgConstants.APPLICATION_KEY, Cat.getManager().getDomain());
            logger.info(" start feign : " + request.getMethod() + " model : rootId = " + rootId + " parentId = " + parentId + " childId = " + childId);
        }
        try {
            return execution.execute(request, body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
